<?php

namespace addons\litestore\controller\api;

use addons\litestore\model\Wxlitestoregoods;
use app\common\controller\Api;
use app\common\controller\Fedex;
use app\common\library\Auth;
use addons\litestore\model\CacheCart;
use addons\litestore\model\Cart as CartModel;
use think\Db;

/**
 * 购物车（现在是在数据库，缓存已弃用）
 * Class Cart
 * @package addons\litestore\controller\api
 */
class Cart extends Api
{
	protected $noNeedLogin = [];
	protected $noNeedRight = ['*'];

    /* @var int $user_id 用户id */
    private $user_id;
    private $model;
    // 错误信息
    protected $error_msg;

	public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->uuid = $this->auth->uuid;
        $this->model = new CartModel($this->user_id, $this->uuid);
    }

    public function getlists()
    {
        $request = $this->request->request();
        if(isset($request['address'])){
            $address = $request['address'];
        }else{
            $address = [];
        }
        if(isset($request['order']) && $request['order']==1){
            $order = 1;
        }else{
            $order = 0;
        }
        //折扣码
        if(isset($request['code'])){
            $code = $request['code'];
        }else{
            $code = '';
        }

        $list = $this->model->getList($request,$address,$order,$code);

        return $this->success('',$list);
    }

    public function hasError()
    {
        return !empty($this->error_msg);
    }

    public function getError()
    {
        return $this->error_msg;
    }

  	/* 加入购物车*/
    public function add()
    {
    	$rq_data = $this->request->request();
    	$goods_id = $rq_data['goods_id'];
    	$goods_num = $rq_data['goods_num'];
    	$goods_sku_id = $rq_data['goods_sku_id'];

        if (!$this->model->add($goods_id, $goods_num, $goods_sku_id)) {
            return $this->error($this->model->getError() ?: '加入购物车失败');
        }
        $total_num = $this->model->getTotalNum();
        return $this->success('加入购物车成功',['cart_total_num' => $total_num]);
    }

    //获得购物车商品数量
    public function getTotalNum(){
        $total_num = $this->model->getTotalNum();
        return $this->success('',['cart_total_num' => $total_num]);
    }

    public function sub(){
        $rq_data = $this->request->request();
        $goods_id = $rq_data['goods_id'];
        $goods_sku_id = $rq_data['goods_sku_id'];
        $this->model->sub($goods_id, $goods_sku_id);
        return $this->success('操作成功');
    }
    public function delete()
    {
        $rq_data = $this->request->request();
        $goods_id = $rq_data['goods_id'];
        $goods_sku_id = $rq_data['goods_sku_id'];
        $this->model->del($goods_id, $goods_sku_id);
        return $this->success('操作成功');
    }

}

